package com.exchange.service.mybatis;

import com.exchange.dto.UserDto;
import com.exchange.entity.User;
import com.exchange.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class MyBatisUserService {
    
    @Autowired
    private UserMapper userMapper;
    
    public Optional<User> findById(Long id) {
        User user = userMapper.selectById(id);
        return Optional.ofNullable(user);
    }
    
    public Optional<User> findByUsername(String username) {
        User user = userMapper.selectByUsername(username);
        return Optional.ofNullable(user);
    }
    
    public Optional<User> findByEmail(String email) {
        User user = userMapper.selectByEmail(email);
        return Optional.ofNullable(user);
    }
    
    public List<UserDto> findAllUsers() {
        return userMapper.selectAllUsers();
    }
    
    public UserDto createUser(User user) {
        // Set creation timestamps
        user.setCreatedAt(java.time.LocalDateTime.now());
        user.setUpdatedAt(java.time.LocalDateTime.now());
        
        // Insert the user
        userMapper.insert(user);
        
        // Return DTO representation
        return UserDto.fromEntity(user);
    }
    
    public UserDto updateUser(Long id, User user) {
        // Find the existing user
        User existingUser = userMapper.selectById(id);
        if (existingUser != null) {
            // Update properties
            existingUser.setUsername(user.getUsername());
            existingUser.setEmail(user.getEmail());
            existingUser.setPhone(user.getPhone());
            existingUser.setUserType(user.getUserType());
            existingUser.setStatus(user.getStatus());
            existingUser.setUpdatedAt(java.time.LocalDateTime.now());
            
            // Perform update in database
            userMapper.update(existingUser);
            
            // Return DTO representation
            return UserDto.fromEntity(existingUser);
        }
        return null;
    }
    
    public boolean deleteUser(Long id) {
        int result = userMapper.deleteById(id);
        return result > 0;
    }
    
    public boolean existsByUsername(String username) {
        return userMapper.existsByUsername(username);
    }
    
    public boolean existsByEmail(String email) {
        return userMapper.existsByEmail(email);
    }
}